#include "FrameBuffer.h"

FrameQueueBuffer::FrameQueueBuffer(size_t maxFrames, size_t frameSize, size_t bufSize) : 
        mFrameSize(frameSize),
        mMaxFrames(maxFrames),        
        mBufferSize(bufSize == 0 ? maxFrames * frameSize : bufSize),
        buffer(mBufferSize, 0),
        writeIndex(0),
        readIndex(0), 
        frameCount(0)
{
    if (mMaxFrames == 0) {
        throw std::invalid_argument("Max frames must be greater than 0");
    }
    if (mBufferSize < mMaxFrames * mFrameSize) {
        throw std::invalid_argument("Buffer size is too small for max frames and frame size");
    }
}

// 写入一帧数据
void FrameQueueBuffer::writeFrame(const uint8_t* frameData, size_t frameSize) {
    if (frameSize != mFrameSize) {
        throw std::invalid_argument("Frame size must be 128KB");
    }

    // 将数据写入缓冲区
    std::copy(frameData, frameData + frameSize, buffer.data() + writeIndex);

    // 更新写入索引
    writeIndex = (writeIndex + mFrameSize) % mBufferSize;

    // 增加帧计数
    frameCount++;

    // 如果帧计数超过mMaxFrames，更新读取索引
    if (frameCount > mMaxFrames) {
        readIndex = (readIndex + mFrameSize) % mBufferSize;
        frameCount = mMaxFrames; // 保持最大帧数限制
    }
}

// 读取数据
size_t FrameQueueBuffer::read(uint8_t* data, size_t size, size_t offset) {
    if (offset >= mMaxFrames * mFrameSize) {
        throw std::out_of_range("Offset out of range");
    }

    // 计算实际读取的起始位置
    size_t actualReadPos = (readIndex + offset) % mBufferSize;

    // 计算实际可读取的字节数
    size_t available = (writeIndex - readIndex + mBufferSize) % mBufferSize;
    size_t toRead = std::min(size, available - (actualReadPos - readIndex));

    // 读取数据
    if (actualReadPos + toRead <= mBufferSize) {
        std::copy(buffer.data() + actualReadPos, buffer.data() + actualReadPos + toRead, data);
    }
    else {
        // 跨越缓冲区边界
        size_t firstPart = mBufferSize - actualReadPos;
        std::copy(buffer.data() + actualReadPos, buffer.data() + mBufferSize, data);
        std::copy(buffer.data(), buffer.data() + toRead - firstPart, data + firstPart);
    }

    return toRead;
}

// 清空缓冲区
void FrameQueueBuffer::clear_data() {
    // 重置缓冲区内容
    std::fill(buffer.begin(), buffer.end(), 0);

    // 重置读写索引
    writeIndex = 0;
    readIndex = 0;
    frameCount = 0;
}

// 获取当前有效数据的总长度
size_t FrameQueueBuffer::getValidDataLength() const {
    return frameCount * mFrameSize;
}
